package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.service.IUnlikeService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UnlikeServiceImpl implements IUnlikeService {

    @Autowired
    MongoTemplate mongoTemplate;

    /*
      记录app端用户不喜欢行为
   */
    @Override
    public ResponseResult saveUnlike(UnLikesBehaviorDto dto) {
        //构建ApUnlikesBehavior对象
        ApUnlikesBehavior unlikesBehavior = new ApUnlikesBehavior();
        User user = AppThreadUtil.getThread();
        if (user == null){
            unlikesBehavior.setEquipmentId(dto.getEquipmentId());
        }else {
            unlikesBehavior.setUserId(user.getUserId());
        }
        unlikesBehavior.setArticleId(dto.getArticleId());
        unlikesBehavior.setType(dto.getType());
        unlikesBehavior.setCreatedTime(new Date());
        //调用mongodb判断用户是否对该文章进行过“不喜欢”操作
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (user != null){
            query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        }else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        if (one == null){
            mongoTemplate.save(unlikesBehavior);
        }else {
            if (one.getType() != dto.getType()){
                one.setType(dto.getType());
            }
            mongoTemplate.save(one);
        }
        return ResponseResult.okResult();
    }

    /*
        查询不喜欢记录
     */
    @Override
    public ResponseResult<ApUnlikesBehavior> getUnlikes(UnLikesBehaviorDto dto) {
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (dto.getUserId() == null){
            query.addCriteria(Criteria.where("equipment").is(dto.getEquipmentId()));
        }else {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        return ResponseResult.okResult(one);
    }
}
